package br.com.erpcortume.DAO;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import br.com.erpcortume.repositorio.UsuarioRepositorio;

@Repository
@Transactional
public class UsuarioDAO implements UsuarioRepositorio{

	private SessionFactory sf;
	
	@Autowired
	public UsuarioDAO(SessionFactory factory) {
		this.sf = factory;
	}
	
	private Session getSession(){
		return sf.getCurrentSession();
	}
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		Query query = getSession().createQuery("from Usuario u where u.login = :login");
		List users = query.setParameter("login", username).list();
		
		if (!users.isEmpty()) {
			return (UserDetails) users.get(0);
		}
		 
		return null;
	}

}
